package com.treeliked.resource;

import com.treeliked.pojo.Response;
import com.treeliked.service.FolderService;
import com.treeliked.service.impl.FolderServiceImpl;
import com.treeliked.util.Constant;
import com.treeliked.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

/**
 * folder resource
 *
 * @author lqs2
 * @date 2018/11/29, Thu
 */
@Path("/folder")
public class FolderResource {


    private static Logger log = LoggerFactory.getLogger(FolderService.class);

    /**
     * 文件夹服务
     */
    private static FolderService fs = new FolderServiceImpl();

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String test() {
        return "CONNECT SUCCESS";
    }


    @GET
    @Path("/mkdir/{name : .+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response createFolder(@Context UriInfo uriInfo) {
        // 从mkdir/后得到参数
        String realPath = getExpectedParams(uriInfo, 13);
        Response response = new Response();

        if (StringUtils.isEmpty(realPath)) {
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            response.setMessage(Constant.PARAM_NULL_INFO);
            return response;
        }
        try {
            fs.createFolder(realPath, response);
        } catch (Exception e) {
            log.error("", e);
            packServerErrorResponse(response);
        }
        return response;
    }

    @GET
    @Path("/rm/{name : .+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response deleteFolder(@Context UriInfo uriInfo) {
        // 从rm/后得到参数
        String realPath = getExpectedParams(uriInfo, 10);

        Response response = new Response();

        try {
            fs.deleteFolder(realPath, response);
        } catch (Exception e) {
            log.error("", e);
            packServerErrorResponse(response);
        }
        return response;
    }

    @GET
    @Path("/ls/{name : .+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response showFolder(@Context UriInfo uriInfo) {
        // 从rm/后得到参数
        String realPath = getExpectedParams(uriInfo, 10);
        Response response = new Response();
        try {
            fs.displayFolder(realPath, response);
        } catch (Exception e) {
            log.error("", e);
            packServerErrorResponse(response);
        }
        return response;
    }


    /**
     * @param uriInfo            uri请求信息
     * @param expectedStartIndex 截取起始位置
     */
    static String getExpectedParams(UriInfo uriInfo, int expectedStartIndex) {
        return uriInfo.getPath().substring(expectedStartIndex);
    }


    static void packServerErrorResponse(Response resp) {
        resp.setCode(Response.RESPONSE_SERVER_ERROR);
        resp.setMessage(Constant.SERVER_ERROR_INFO);
    }

}
